package com.lf.web.action.system;

import com.lf.data.*;
import com.lf.data.dao.WebNodeContentDAO;
import com.lf.data.dao.WebNodeOptionDAO;
import com.lf.data.dao.TemplateDAO;
import com.lf.data.search.Field;
import com.lf.data.search.Query;
import com.lf.web.html.MakeHtml;
import com.lf.web.service.system.webnode.WebNode;
import com.lf.web.service.system.webnode.WebNodeDAO;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.json.JSONObject;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChannelHtmlService extends ActionSupport implements ServletResponseAware {

    private HttpServletResponse res;
    private static final Logger LOGGER = Logger.getLogger(ChannelHtmlService.class);
    private WebNodeDAO channeldao;
    private WebNodeOptionDAO channeloptiondao;
    private WebNodeContentDAO channelcontentdao;
    private TemplateDAO templatedao;

    private int pagecount = 20;

    private String id = "";
    private String channelid = "";

    public void setChanneldao(WebNodeDAO channeldao) {
        this.channeldao = channeldao;
    }

    public void setChanneloptiondao(WebNodeOptionDAO channeloptiondao) {
        this.channeloptiondao = channeloptiondao;
    }

    public void setChannelcontentdao(WebNodeContentDAO channelcontentdao) {
        this.channelcontentdao = channelcontentdao;
    }

    public void setTemplatedao(TemplateDAO templatedao) {
        this.templatedao = templatedao;
    }

    @Override
    public void setServletResponse(HttpServletResponse res) {
        this.res = res;
    }

    public void setPagecount(int pagecount) {
        this.pagecount = pagecount;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setChannelid(String channelid) {
        this.channelid = channelid;
    }

    public void make() throws IOException {
        if (Validate.check(Validate.OBJECTID, id)) {
            JSONObject json = new JSONObject();
            boolean canMake = false;
            WebNodeContent channelcontent = new WebNodeContent(channelcontentdao.findById(id));
            String channelid = channelcontent.getString(channelcontent.WebNodeId);
            WebNode webNode = new WebNode(channeldao.findById(channelid));
            String rootpath = ServletActionContext.getServletContext().getRealPath("/");
            String outfile = "";
            switch (webNode.getString(webNode.TYPE)) {
                case "article": // 内容显示
                    canMake = true;
                    outfile = webNode.getString(webNode.KEY) + ".html";
                    break;
                case "list":
                    canMake = true;
                    outfile = webNode.getString(webNode.KEY) + "/" + id + ".html";
                    break;
                case "url":
                default:
            }
            if (canMake) {

                String templateid = webNode.getString(webNode.TEMPLATE_ID);
                if (templateid.equals("")) {
                    json.put("code", 3);
                    json.put("msg", "该模块尚未设置内容模板");
                } else {
                    Template template = new Template(templatedao.findById(templateid));
                    String templatefile = rootpath + template.getString(template.Path);

                    MakeHtml make = new MakeHtml();
                    make.setData(channelcontent);
                    make.setOutfile(rootpath + outfile);
                    make.setTemplatefile(templatefile);
                    if (make.OutHtml()) {
                        json.put("code", 1);
                        json.put("msg", "页面输出成功");
                        json.put("url", outfile);
                    } else {
                        json.put("code", 1);
                        json.put("msg", "页面输出失败");
                    }
                }
            } else {
                json.put("code", 2);
                json.put("msg", "该模块没有内容可以输出");
            }
            res.getWriter().write(json.toString());
        } else {
            LOGGER.error("非法请求生成静态页面：id=" + id);
            res.sendError(404);
        }
    }

    public void makeList() throws IOException {
        if (Validate.check(Validate.OBJECTID, id)) {
            JSONObject json = new JSONObject();
            WebNode webNode = new WebNode(channeldao.findById(channelid));
            if ("list".equals(webNode.getString(webNode.TYPE))) {

                String templateid = webNode.getString(WebNode.LIST_TEMPLATE);
                if (templateid.equals("")) {
                    json.put("code", 3);
                    json.put("msg", "该模块尚未设置列表模板");
                } else {
                    String rootpath = ServletActionContext.getServletContext().getRealPath("/");

                    Template template = new Template(templatedao.findById(templateid));
                    String templatefile = rootpath + template.getString(template.Path);
                    String channelname = webNode.getString(webNode.NAME);
                    WebNodeOption co = new WebNodeOption();
                    Query query = new Query();
                    query.eq(co.List, 1);
                    Field field = new Field();
                    field.include(co.Name);
                    List<Cluster> listoption = channeloptiondao.find(query, field, null);
                    WebNodeContent channelfield = new WebNodeContent();
                    for (Map<String, Object> map : listoption) {
                        try {
                            channelfield.put(map.get(co.Name).toString(), 1);
                        } catch (Exception e) {
                            LOGGER.error("错误选项");
                        }
                    }
                    channelfield.put(channelfield.Created, 1);
                    WebNodeContent cc = new WebNodeContent();
                    query.clear();
                    query.eq(cc.WebNodeId, channelid);
                    WebNodeContent channelsort = new WebNodeContent();
                    channelsort.put(channelsort.Created, 1);

                    long listcount = channelcontentdao.count(query);
                    long pagesum = listcount / pagecount;
                    if (listcount % pagecount > 0)
                        pagesum++;
                    if (pagesum == 0)
                        pagesum = 1;

                    MakeHtml make = new MakeHtml();
                    make.setTemplatefile(templatefile);
                    int makecount = 0;
                    for (int pagenumber = 0; pagenumber < pagesum; pagenumber++) {
                        Map<String, Object> data = new HashMap<String, Object>();
                        List<Map<String, Object>> datalist = null;//channeldao.finds(search, channelfield, channelsort, pagenumber, pagecount);
                        data.put("list", datalist);
                        data.put("sum", listcount); // 总数
                        data.put("pagesum", pagesum); // 总页数
                        data.put("pagenumber", pagenumber); // 页号
                        data.put("pagecount", pagecount); // 页面大小
                        data.put("pagesize", datalist.size()); // 当前页大小
                        make.setData(data);
                        make.setOutfile(rootpath + channelname + "/" + pagenumber + ".html");
                        if (!make.OutHtml())
                            break;
                        else
                            makecount++;
                    }
                    if (makecount == pagesum) {
                        json.put("code", 1);
                        json.put("msg", "列表页面全部成功输出");
                    } else {
                        json.put("code", 1);
                        json.put("msg", "列表页面全部成功输出");
                    }
                    json.put("makecount", makecount);
                }
            } else {
                json.put("code", 2);
                json.put("msg", "该模块没有列表信息可以输出");
            }
            res.getWriter().write(json.toString());
        } else {
            LOGGER.error("非法请求生成列表静态页面：id=" + id);
            res.sendError(404);
        }
    }
}
